package com.ants.boot.system.controller;

import com.ants.boot.core.Response;
import com.ants.boot.system.dto.sysuser.SendCaptchaDto;
import com.ants.boot.utils.PhoneCodeUtils;
import com.ants.boot.utils.RedisUtils;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 蚂蚁会花呗
 * @date 2022/2/16 18:19
 * 验证码
 */
@RestController
@RequestMapping("/ants")
@Api(tags = "验证码")
public class CaptchaController {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 验证码
     */
    @GetMapping(value = "captcha")
    @ApiOperation(value="验证码",notes="获取验证码")
    public Response login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SpecCaptcha captcha = new SpecCaptcha(130, 48,4);
        String verCode = captcha.text().toUpperCase();
        String key = UUID.randomUUID().toString();
        redisUtils.set(key,verCode,300);
        Map<String,Object> map = new HashMap<>();
        map.put("key",key);
        map.put("image",captcha.toBase64());
        return Response.okData(map);
    }

    /***
     * 登录时发送验证码
     * @return
     */
    @PostMapping("send_captcha")
    public Response sendOfLogin(@RequestBody @Validated SendCaptchaDto dto){
        return Response.okData(getCaptcha(dto));
    }

    private String getCaptcha(SendCaptchaDto dto) {
        //todo 模拟发送验证码.五分钟
        String randomCode = PhoneCodeUtils.getRandomCode();
        redisUtils.set(PhoneCodeUtils.codeStartWith(dto.getUsername()), randomCode, 300L);
        return randomCode;
    }
}
